<template>
  <view class="wallpaper-grid">
    <view class="grid-container">
      <view 
        v-for="(item, index) in wallpaperList" 
        :key="item._id"
        class="wallpaper-item"
        :class="{ 'left-column': index % 2 === 0, 'right-column': index % 2 === 1 }"
        @click="handleWallpaperClick(item)"
      >
        <view class="wallpaper-wrapper">
          <image 
            :src="item.imageUrl" 
            mode="aspectFill" 
            lazy-load
            class="wallpaper-image"
            @error="handleImageError(index)"
          />
          <view class="wallpaper-overlay" v-if="!item.imageUrl && !item.file_url">
            <text>图片加载失败</text>
          </view>
          <view class="wallpaper-info">
            <view class="wallpaper-title">{{ item.title }}</view>
            <view class="wallpaper-stats">
              <view class="stat-item" @click.stop="handleFavorite(item)">
                <view 
                  :class="['icon', item.is_favorite ? 'icon-heart-filled' : 'icon-heart']" 
                  :style="{ color: item.is_favorite ? '#ff4d4f' : '#fff' }"
                >
                  {{ item.is_favorite ? '❤️' : '🤍' }}
                </view>
                <text>{{ item.favorites || 0 }}</text>
              </view>
              <view class="stat-item">
                <view class="icon icon-download" style="color: #fff">⬇️</view>
                <text>{{ item.downloads || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore">
      <view class="load-more-content">
        <text v-if="loadStatus === 'loading'">加载中...</text>
        <text v-else-if="loadStatus === 'more'">上拉加载更多</text>
        <text v-else>没有更多了</text>
      </view>
    </view>
    <!-- 空状态 -->
    <view class="empty-state" v-if="wallpaperList.length === 0 && loadStatus !== 'loading'">
      <view class="icon icon-image" style="font-size: 64px; color: #999">🖼️</view>
      <text class="empty-text">暂无壁纸</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useToken } from '@/common/token.js';

const { token, isValid, loadToken } = useToken();

const props = defineProps({
  wallpaperList: {
    type: Array,
    default: () => []
  },
  hasMore: {
    type: Boolean,
    default: false
  },
  loadStatus: {
    type: String,
    default: 'more'
  }
});

const emit = defineEmits(['wallpaperClick', 'loadMore', 'favorite']);

const contentText = {
  contentdown: '上拉加载更多',
  contentrefresh: '加载中...',
  contentnomore: '没有更多了'
};

// 处理壁纸点击
const handleWallpaperClick = (item) => {
	console.log('canshu',item);
  emit('wallpaperClick', item);
};

// 处理收藏
  const handleFavorite = async (wallpaper) => {
    await loadToken(); // 确保token已加载
    if (!isValid()) {
      uni.navigateTo({
        url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
      });
      return;
    }
    
    try {
      // 调用云函数
      const res = await uniCloud.callFunction({
        name: 'toggle',
        data: {
          wallpaper_id: wallpaper._id,
          uniIdToken: token.value
        }
      });
      
      console.log('收藏操作调用云函数返回:', res);
      
      if (res.result.code === 0) {
        // 操作成功
        const index = props.wallpaperList.findIndex(item => item._id === wallpaper._id);
        if (index !== -1) {
          // 发出更新事件
          emit('favorite', {
            ...wallpaper,
            is_favorite: res.result.data.is_favorite,
            favorites: res.result.data.favorites
          });
        }
        
        uni.showToast({
          title: res.result.message || (res.result.data.is_favorite ? '收藏成功' : '取消收藏'),
          icon: 'success',
          duration: 2000
        });
      } else if (res.result.code === 401) {
        // 处理认证错误
        console.log('接收到401错误，token状态:', res.result.tokenStatus);
        
        // 如果是token过期或错误，先尝试刷新token再决定是否跳转
        if (res.result.tokenStatus === 'expired' || res.result.tokenStatus === 'error') {
          console.log('token可能过期或错误，尝试刷新后重试...');
          await loadToken();
          // 延迟一点时间让token加载完成
          await new Promise(resolve => setTimeout(resolve, 100));
          
          if (token.value) {
            // 重试一次
            handleFavorite(wallpaper);
          } else {
            uni.navigateTo({
              url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
            });
          }
        } else {
          // 如果确实是未提供token，则跳转到登录页面
          uni.navigateTo({
            url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
          });
        }
      } else {
        // 其他错误
        uni.showToast({
          title: res.result.message || '操作失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('收藏操作异常:', error);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      });
    }
    
    // 事件通知已通过favorite事件完成，不需要重复发出
  };


// 处理图片加载错误
const handleImageError = (index) => {
  console.error(`图片加载失败: 索引 ${index}`);
};

// 触底加载更多
const handleScrollToBottom = () => {
  if (props.hasMore && props.loadStatus !== 'loading') {
    emit('loadMore');
  }
};
</script>

<style lang="less" scoped>
.icon {
  font-size: 18px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.load-more-content {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 28rpx;
}
.wallpaper-grid {
  padding: 0 8px;
  .grid-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .wallpaper-item {
      width: calc(50% - 4px);
      margin-bottom: 12px;
      animation: fadeIn 0.3s ease-in;
      &.left-column {
        animation-delay: 0s;
      }
      &.right-column {
        animation-delay: 0.1s;
      }
      .wallpaper-wrapper {
        position: relative;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        background-color: #f5f5f5;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        &:active {
          transform: scale(0.98);
        }
        .wallpaper-image {
          width: 100%;
          display: block;
          min-height: 200px;
        }
        .wallpaper-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #999;
        }
        .wallpaper-info {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          padding: 8px 12px;
          background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
          .wallpaper-title {
            color: #fff;
            font-size: 14px;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .wallpaper-stats {
            display: flex;
            align-items: center;
            gap: 16px;
            .stat-item {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #fff;
              font-size: 12px;
              &:active {
                opacity: 0.8;
              }
            }
          }
        }
      }
    }
  }
  .load-more {
    padding: 20px 0;
  }
  .empty-state {
    padding: 60px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .empty-text {
      margin-top: 16px;
      color: #999;
      font-size: 16px;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>